package com.yzs.utils;

import com.yzs.entity.Admin;
import com.yzs.entity.User;
import com.yzs.service.Impl.RedisServiceImpl;
import com.yzs.service.RedisService;
import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * Jwt工具
 */
@Component
public class JwtUtil {
    private final long time = 1000 * 60 * 60 * 24;
    private final String ADMIN_SUBJECT = "Admin-Login";
    private final String USER_SUBJECT = "User-Login";
    private final String signature = "admin";
    private final String userSignature = "user";
    private JwtBuilder jwtBuilder = Jwts.builder();
    @Autowired
    RedisService redisService;
//    private static HashMap<String, Integer> tokenMap = new HashMap<>();
//    private static HashMap<String, Integer> userTokenMap = new HashMap<>();

    /**
     * username && role 创建token
     *
     * @param admin
     * @return null 则表示存在token
     */
    public String createToken(Admin admin) {
        String token = jwtBuilder
                // header
                .setHeaderParam("typ", "jwt")
                .setHeaderParam("alg", "HS256")
                // payload
                .claim("id", admin.getId())
                .claim("username", admin.getUsername())
                .claim("role", admin.getRole())
                // 主题
                .setSubject(ADMIN_SUBJECT)
                // 有效时间
                .setExpiration(new Date(System.currentTimeMillis() + time))
                // id值
                .setId(UUID.randomUUID().toString())
                // 签名信息
                .signWith(SignatureAlgorithm.HS256, signature)
                // "." 拼接
                .compact();

        redisService.set(ADMIN_SUBJECT+"_"+admin.getId(),token, TimeUnit.MILLISECONDS.toSeconds(time));
            return token;
    }

    public String createUserToken(User user){
        String token = jwtBuilder
                // header
                .setHeaderParam("typ", "jwt")
                .setHeaderParam("alg", "HS256")
                // payload
                .claim("id", user.getId())
                .claim("username", user.getUsername())
                .claim("name", user.getName())
                // 主题
                .setSubject(USER_SUBJECT)
                // 有效时间
                .setExpiration(new Date(System.currentTimeMillis() + time))
                // id值
                .setId(UUID.randomUUID().toString())
                // 签名信息
                .signWith(SignatureAlgorithm.HS256, userSignature)
                // "." 拼接
                .compact();
        redisService.set(USER_SUBJECT+"_"+user.getId(),token,time);
            return token;

    }

    /**
     * 验证传入的token是否符合标准 不符合标准返回-1 否则返回用户id
     *
     * @param token
     * @return
     */
    public Integer verifyToken(String token) {
        if (!Objects.isNull(token)) {
            JwtParser parser = Jwts.parser();
        Jws<Claims> claimsJws;
            try {
                claimsJws = parser.setSigningKey(signature).parseClaimsJws(token);
            } catch (Exception e) {
                return -1;
            }
            Integer id = (Integer) claimsJws.getBody().get("id");
            if (id != null) {
                return id;
            } else {
                return -1;
            }
        }
        return -1;
    }
    public Integer verifyUserToken(String token) {
        if (!Objects.isNull(token)) {
            JwtParser parser = Jwts.parser();
        Jws<Claims> claimsJws;
            try {
                claimsJws = parser.setSigningKey(userSignature).parseClaimsJws(token);
            } catch (Exception e) {
                return -1;
            }
            Integer id = (Integer) claimsJws.getBody().get("id");
            if (id != null) {
                return id;
            } else {
                return -1;
            }
        }
        return -1;
    }

    /**
     * 通过token获取管理用户信息
     * @param token
     * @return
     */
    public Jws<Claims> getTokenAdminInfo(String token) {
        if (!Objects.isNull(token)) {
            JwtParser parser = Jwts.parser();
            if (verifyToken(token) != -1) {
                try {
                    return parser.setSigningKey(signature).parseClaimsJws(token);
                } catch (Exception e) {
                    return null;
                }
            }
        }
        return null;
    }
    public Jws<Claims> getTokenUserInfo(String token) {
        if (!Objects.isNull(token)) {
            JwtParser parser = Jwts.parser();
            if (verifyUserToken(token) != -1) {
                try {
                    return parser.setSigningKey(userSignature).parseClaimsJws(token);
                } catch (Exception e) {
                    return null;
                }
            }
        }
        return null;
    }


    /**
     * 判断token是否为空 不为空去redis缓存里将对应的token删除
     *
     * @param token
     * @return
     */
    public boolean removeToken(String token) {
        if (Objects.isNull(token)) {
            return false;
        }
        Jws<Claims> tokenAdminInfo = getTokenAdminInfo(token);
        if(Objects.isNull(tokenAdminInfo)){
           return false;
        }
        Integer id = (Integer) tokenAdminInfo.getBody().get("id");
        return redisService.del(ADMIN_SUBJECT+"_"+id);
    }
    public boolean removeUserToken(String token) {
        if (Objects.isNull(token)) {
            return false;
        }
        Jws<Claims> tokenUserInfo = getTokenUserInfo(token);
        if(Objects.isNull(tokenUserInfo)){
            return false;
        }
        Integer id = (Integer) tokenUserInfo.getBody().get("id");
        return redisService.del(USER_SUBJECT+"_"+id);
    }

}


